/* 
 * Copyright 2011 QDSS.org. All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.qdss.oapi4j.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.CoreConnectionPNames;
import org.qdss.oapi4j.InvokeFailureException;

/**
 * 
 * @author <a href="mailto:zhaofang123@gmail.com">Zhao Fangfang</a>
 * @date 2011-3-20
 * @version $Id: HttpClientFetcher.java 38 2011-09-27 08:48:34Z zhaofang123@gmail.com $
 */
public class HttpClientFetcher {
	
	final private HttpClient httpClient;
	
	/**
	 */
	public HttpClientFetcher() {
		this(100);
	}
	
	/**
	 * @param maxConn
	 */
	public HttpClientFetcher(int maxConn) {
		ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
		cm.setMaxTotal(maxConn);
		httpClient = new DefaultHttpClient(cm);
		httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5 * 1000);
		httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20 * 1000);
	}
	
	/**
	 * @return
	 */
	public HttpClient getHttpClient() {
		return httpClient;
	}
	
	/**
	 * @param request
	 * @return
	 * @throws InvokeFailureException
	 * @throws IOException
	 */
	public HttpResponse execute(HttpUriRequest request) throws InvokeFailureException, IOException {
		HttpResponse response = null;
		request.addHeader("User-Agent", "org.qdss.oapi4j/Java" + System.getProperty("java.version"));
		try {
			response = getHttpClient().execute(request);
			StatusLine line = response.getStatusLine();
			if (line.getStatusCode() != HttpStatus.SC_OK) {
				throw new InvokeFailureException(line.toString());
			}
		} catch (IOException ex) {
			throw ex;
		}
		return response;
	}
	
	/**
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public String parseResponseText(HttpResponse response) throws IOException {
		String responseText = null;
		InputStream stream = null;
		BufferedReader reader = null;
		try {
			stream = response.getEntity().getContent();
			if (stream.available() > -1) {
				reader = new BufferedReader(new InputStreamReader(stream, ApiUtils.ENCODING_DEFAULT));

				StringBuffer sb = new StringBuffer();
				char[] buffer = new char[1024 * 4];
				int read = -1;
				while ((read = reader.read(buffer)) > 0) {
					char[] chunk = new char[read];
					System.arraycopy(buffer, 0, chunk, 0, read);
					sb.append(chunk);
				}
				responseText = sb.toString();
			}
		} catch (IOException ex) {
			throw ex;
		} finally {
			try {
				stream.close();
			} catch (Exception ex){}
			try {
				reader.close();
			} catch (Exception ex){}
		}
		return responseText;
	}
}
